//
//  LWS_ClassifyViewController.m
//  GiftYY
//
//  Created by dllo on 16/3/10.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "LWS_ClassifyViewController.h"
#import "LWS_ClassifyCollectionViewCell.h"
#import "LWS_CollectionReusableView.h"
#import "LWS_ItemViewController.h"
#import "LWS_JumpViewController.h"
#import "LWS_GiftJumpViewController.h"
#import "LWS_GiftHxmIViewController.h"
#import "LWS_SearchViewController.h"
#import "LWS_ Classifymodel.h"
#define WIDTH    [UIScreen mainScreen].bounds.size.width / 414
#define HEIGHT   [UIScreen mainScreen].bounds.size.height / 736
@interface LWS_ClassifyViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UITableViewDataSource,UITableViewDelegate>

@property (strong, nonatomic) IBOutlet UICollectionView *classifyCollectionView;
//@property(nonatomic, retain)UISegmentedControl *segMentedControl;

@property(strong, nonatomic)NSMutableArray *groupsArr;
@property(strong, nonatomic)NSMutableArray *channerArr;//
@property (strong, nonatomic) IBOutlet UICollectionViewFlowLayout *flowLayout;
@property (strong, nonatomic) IBOutlet UICollectionView *heardCollectionView;
@property(nonatomic, retain)NSMutableArray *collArr;//轮播图片
@property (strong, nonatomic) IBOutlet UICollectionViewFlowLayout *heardFolwLayout;
@property (strong, nonatomic) IBOutlet UIView *titleView;
@property (strong, nonatomic) IBOutlet UITableView *giftTableView;
@property (strong, nonatomic) IBOutlet UICollectionView *gift_CollectionView;
@property (strong, nonatomic) IBOutlet UICollectionViewFlowLayout *gift_flowLayout;
@property(nonatomic, retain)NSMutableArray *giftArr;//礼物页数组
@property(nonatomic, retain)UISegmentedControl *segMented;
- (IBAction)selectButton:(id)sender;
- (IBAction)selectButtonNo:(id)sender;
@property (strong, nonatomic) IBOutlet UIButton *selectButton;
@property (strong, nonatomic) IBOutlet UIButton *selectButtonNo;
@property (strong, nonatomic) IBOutlet UIView *gifiView;
@property (nonatomic, retain) UIButton *searchButton;




@end

@implementation LWS_ClassifyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [self createNetWork];
    [self createSegMented];
    
     self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:1.000 green:0.445 blue:0.525 alpha:1.000];
//    self.navigationController.navigationBar.translucent = NO;
    
    //攻略下面瀑布流
    [self.classifyCollectionView setCollectionViewLayout:self.flowLayout];
    
    //头视图瀑布流
    [self.heardCollectionView setCollectionViewLayout:self.heardFolwLayout];

    
    //礼物瀑布流
    [self.gift_CollectionView setCollectionViewLayout:self.gift_flowLayout];
    
    //下面瀑布流注册
    [self.classifyCollectionView registerNib:[UINib nibWithNibName:NSStringFromClass([LWS_ClassifyCollectionViewCell class]) bundle:nil] forCellWithReuseIdentifier:NSStringFromClass([LWS_ClassifyCollectionViewCell class])];
   //上面瀑布流注册
    [self.heardCollectionView registerNib:[UINib nibWithNibName:NSStringFromClass([LWS_ClassifyCollectionViewCell class]) bundle:nil] forCellWithReuseIdentifier:NSStringFromClass([LWS_ClassifyCollectionViewCell class])];
    //礼物页面瀑布流注册
    [self.gift_CollectionView registerNib:[UINib nibWithNibName:NSStringFromClass([LWS_ClassifyCollectionViewCell class]) bundle:nil] forCellWithReuseIdentifier:NSStringFromClass([LWS_ClassifyCollectionViewCell class])];
    
    //设置上边横着滚动
    self.heardFolwLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
//    self.heardCollectionView.bounces = NO;
    //设置下面瀑布流标题注册
    [self.classifyCollectionView registerNib:[UINib nibWithNibName:NSStringFromClass([LWS_CollectionReusableView class]) bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:NSStringFromClass([LWS_CollectionReusableView class])];
    //设置上面瀑布流标题注册
    [self.heardCollectionView registerNib:[UINib nibWithNibName:NSStringFromClass([LWS_CollectionReusableView class]) bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:NSStringFromClass([LWS_CollectionReusableView class])];
    self.classifyCollectionView.backgroundColor = [UIColor whiteColor];
    
    //礼物页面分区标题
//    [self.gift_CollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"path"];
     [self.gift_CollectionView registerNib:[UINib nibWithNibName:NSStringFromClass([LWS_CollectionReusableView class]) bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:NSStringFromClass([LWS_CollectionReusableView class])];
    self.gift_CollectionView.backgroundColor = [UIColor whiteColor];
    
    //礼物页tableView注册
    [self.giftTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"reuse2"];
   
    //添加通知中心
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(center) name:@"seg" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(returnApp) name:@"return" object:nil];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"iconfont-fanhui.png"] style:1 target:self action:@selector(classApp)];
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    
    
    
}
-(void)classApp{

    if (self.segMented.selectedSegmentIndex == 0) {
        self.segMented.hidden = YES;
        self.searchButton.hidden = YES;
    }else{
        self.segMented.hidden = YES;
        self.searchButton.hidden = YES;
    
    }

    [self.navigationController popViewControllerAnimated:YES];
    
}

//实现方法
-(void)center
{
    self.segMented.hidden = NO;
    
}

-(void)returnApp{

    self.searchButton.hidden = NO;

    self.segMented.hidden = NO;
}
- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark 创建segMented
-(void)createSegMented{

    self.segMented = [[UISegmentedControl alloc]initWithItems:@[@"攻略",@"礼物"]];
    [self.segMented addTarget:self action:@selector(segment:) forControlEvents:UIControlEventValueChanged];
    [self.navigationController.view addSubview:self.segMented];
    self.segMented.backgroundColor = [UIColor clearColor];
    self.segMented.tintColor = [UIColor whiteColor];
  
 
    
    
    
    self.segMented.selectedSegmentIndex = 0;
    self.giftTableView.hidden = YES;
    self.gift_CollectionView.hidden = YES;
    self.selectButton.hidden = YES;
    self.selectButtonNo.hidden = YES;
    self.gifiView.hidden = YES;
    
    [self.segMented mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(25);
        make.left.mas_equalTo(self.navigationController.view).offset(80);
        make.width.mas_equalTo(240 * WIDTH);
        make.height.mas_equalTo(30 * HEIGHT);
        
        
    }];
    self.searchButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.searchButton addTarget:self action:@selector(searchB:) forControlEvents:UIControlEventTouchUpInside];
    [self.searchButton setImage:[UIImage imageNamed:@"iconfont-sousuo.png"] forState:UIWindowLevelNormal];
    [self.navigationController.view addSubview:self.searchButton];
    [self.searchButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(25 * HEIGHT);
        make.left.mas_equalTo(self.navigationController.view).offset(350 * WIDTH);
        make.width.mas_equalTo(40 * WIDTH);
        make.height.mas_equalTo(30 * HEIGHT);
        
    }];
    
    
}
#pragma mark 搜索跳转
-(void)searchB:(UIButton *)button{

//    LWS_SearchViewController *searchVC = [[LWS_SearchViewController alloc] init];
//    [self.navigationController pushViewController:searchVC animated:YES];
//    self.searchButton.hidden = YES;
//    self.segMented.hidden = YES;
}



-(void)segment:(UISegmentedControl *)segment{

    if (segment.selectedSegmentIndex == 0) {
       self.giftTableView.hidden = YES;
        self.heardCollectionView.hidden = NO;
        self.gifiView.hidden = YES;
        self.classifyCollectionView.hidden = NO;
        self.gift_CollectionView.hidden = YES;
        self.searchButton.hidden = NO;
        self.selectButton.hidden = YES;
        self.selectButtonNo.hidden = YES;
       
        segment.selectedSegmentIndex = 0;
    }else if(segment.selectedSegmentIndex == 1){
        self.heardCollectionView.hidden = YES;
        self.gifiView.hidden = NO;
        self.classifyCollectionView.hidden = YES;
        self.giftTableView.hidden = NO;
        self.gift_CollectionView.hidden = NO;
        self.selectButton.hidden = NO;
        self.selectButtonNo.hidden = NO;
        self.searchButton.hidden = YES;
        
    }
    
   

}

#pragma mark 数据解析
-(void)createNetWork{


    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:@"http://api.liwushuo.com/v2/channel_groups/all" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
            NSDictionary *dataDic = responseObject[@"data"];
        
            self.groupsArr = dataDic[@"channel_groups"];

        
        
            self.channerArr = [NSMutableArray array];
            for (NSDictionary *temp in self.groupsArr) {
                LWS__Classifymodel *model = [[LWS__Classifymodel alloc]init];
                [model setValuesForKeysWithDictionary:temp];
                [self.channerArr addObject:model];
            }
        
        
            [self.classifyCollectionView reloadData];
       
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        
        
        
    }];
    
    AFHTTPSessionManager *managerSec =[AFHTTPSessionManager manager];
    [managerSec GET:@"http://api.liwushuo.com/v2/collections?limit=6&offset=0" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSArray *secArr = responseObject[@"data"][@"collections"];
        self.collArr = [NSMutableArray array];
        for (NSDictionary *dic in secArr) {
            LWS__Classifymodel *model = [[LWS__Classifymodel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.collArr addObject:model];
            
        }
        [self.heardCollectionView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    }];
    AFHTTPSessionManager *managerGift = [AFHTTPSessionManager manager];
    [managerGift GET:@"http://api.liwushuo.com/v2/item_categories/tree" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSArray *gifArr = responseObject[@"data"][@"categories"];
        
        self.giftArr = [NSMutableArray array];
        for (NSDictionary *dic in gifArr) {
            LWS__Classifymodel *model = [[LWS__Classifymodel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.giftArr addObject:model];
            
        }
        [self.giftTableView reloadData];
        [self.gift_CollectionView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    }];


}

#pragma mark 礼物页tableView数量
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.giftArr.count;
    
}

#pragma mark 礼物页tableView标识
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuse2" forIndexPath:indexPath];
    LWS__Classifymodel *gift = self.giftArr[indexPath.row];
    cell.textLabel.text = gift.name;
    cell.textLabel.font = [UIFont systemFontOfSize:15];
    
    return cell;
    
}

#pragma mark collection分区
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    if (collectionView == self.classifyCollectionView) {
        return self.channerArr.count;
    }else if (collectionView == self.gift_CollectionView){
  
        return self.giftArr.count;
    }else{
        
      return 1;
    }

}
#pragma mark collection个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (collectionView == self.classifyCollectionView) {
         return [self.channerArr[section]channels].count;;
    }else if(collectionView == self.gift_CollectionView){
        return [self.giftArr[section] subcategories].count;
    }else{
    
    return self.collArr.count;
    }
}
#pragma mark collection分区标题高度
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    if (collectionView == self.classifyCollectionView) {
        return CGSizeMake(self.view.frame.size.width, 35);
    }else if (collectionView == self.gift_CollectionView){
    
        if (section == 0) {
            return CGSizeMake(0, 0);
        }else{
        return CGSizeMake(self.view.frame.size.width, 45);
        }
    }else{
     return CGSizeMake(0, 0);
    
    }
}

#pragma mark collection重用
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

    if (collectionView == self.classifyCollectionView) {
        LWS__Classifymodel *model = self.channerArr[indexPath.section];
        LWS_ClassifyCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([LWS_ClassifyCollectionViewCell class]) forIndexPath:indexPath];
        
        [cell.backImageView setImageWithURL:[NSURL URLWithString:model.channels[indexPath.row][@"icon_url"]]];
        cell.nameLabel.text = model.channels[indexPath.row][@"name"];
        
        return cell;

    }else if(collectionView == self.gift_CollectionView){
    
        LWS__Classifymodel *model = self.giftArr[indexPath.section];
        LWS_ClassifyCollectionViewCell *gift = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([LWS_ClassifyCollectionViewCell class]) forIndexPath:indexPath];
        [gift.backImageView setImageWithURL:[NSURL URLWithString:model.subcategories[indexPath.row][@"icon_url"]]];
        gift.nameLabel.text = model.subcategories[indexPath.row][@"name"];

        return gift;
    
    }else{
        
        LWS_ClassifyCollectionViewCell *heard = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([LWS_ClassifyCollectionViewCell class]) forIndexPath:indexPath];
        
        LWS__Classifymodel *model = self.collArr[indexPath.row];
        heard.nameLabel.text = model.title;
        [heard.backImageView setImageWithURL:[NSURL URLWithString:model.cover_image_url]];
        return heard;
    }
}

#pragma mark 分区内容
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
//
    if (collectionView == self.classifyCollectionView) {
        LWS_CollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:NSStringFromClass([LWS_CollectionReusableView class]) forIndexPath:indexPath];
//
        view.label.text = [self.channerArr[indexPath.section] name];
//
        return view;
    }else if(collectionView == self.heardCollectionView){
    
        UICollectionReusableView *viee = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"path" forIndexPath:indexPath];
        
        
        return viee;
    
    }else{
        LWS_CollectionReusableView *reusa = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:NSStringFromClass([LWS_CollectionReusableView class]) forIndexPath:indexPath];

            LWS__Classifymodel *model = self.giftArr[indexPath.section];
            reusa.label.text = [NSString stringWithFormat:@"--------------- %@ ---------------",model.name];
        reusa.label.font = [UIFont systemFontOfSize:15];
        reusa.label.textAlignment = 1;
            return reusa;

}
}


#pragma mark 点击方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{

    if (collectionView == self.classifyCollectionView) {
        LWS_ItemViewController *item = [[LWS_ItemViewController alloc] initWithNibName:NSStringFromClass([LWS_ItemViewController class]) bundle:nil];
        [self.navigationController pushViewController:item animated:YES];
        
        self.segMented.hidden = YES;
        self.searchButton.hidden = YES;
        LWS__Classifymodel *model = self.channerArr[indexPath.section];
        item.backID = model.channels[indexPath.row][@"id"];
        item.titleName = model.channels[indexPath.row][@"name"];
    }else if(collectionView == self.heardCollectionView){
    
        LWS_ItemViewController *heardItem = [[LWS_ItemViewController alloc]initWithNibName:NSStringFromClass([LWS_ItemViewController class]) bundle:nil];
        [self.navigationController pushViewController:heardItem animated:YES];
        LWS__Classifymodel *model = self.collArr[indexPath.row];
        self.segMented.hidden = YES;
        
        heardItem.appID = model.appId;
        
    }else if(collectionView == self.gift_CollectionView){
    
        LWS_GiftJumpViewController *giftVC = [[LWS_GiftJumpViewController alloc] initWithNibName:NSStringFromClass([LWS_GiftJumpViewController class]) bundle:nil];
        self.segMented.hidden = YES;
        [self.navigationController pushViewController:giftVC animated:YES];
        LWS__Classifymodel *model = self.giftArr[indexPath.section];
        giftVC.appID = model.subcategories[indexPath.row][@"id"];
        giftVC.titleName = model.subcategories[indexPath.row][@"name"];
  
//        [self.giftTableView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:indexPath.row] atScrollPosition:UICollectionViewScrollPositionTop animated:YES];

        
        
    }
    
}

-(void)viewWillAppear:(BOOL)animated{
    
    self.tabBarController.tabBar.hidden = NO;
    
}
#pragma mark tableView点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    [self.gift_CollectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:indexPath.row] atScrollPosition:UICollectionViewScrollPositionTop animated:YES];
}


#pragma mark 视图跟动

//- (void)didReceiveMemoryWarning {
//    [super didReceiveMemoryWarning];
//    // Dispose of any resources that can be recreated.
//}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


- (IBAction)selectButton:(id)sender {
    
    LWS_GiftHxmIViewController *giftHxm = [[LWS_GiftHxmIViewController alloc] initWithNibName:NSStringFromClass([LWS_GiftHxmIViewController class]) bundle:nil];
    [self.navigationController pushViewController:giftHxm animated:YES];
    self.segMented.hidden = YES;
    
    
    
    
}

- (IBAction)selectButtonNo:(id)sender {
    
    LWS_GiftHxmIViewController *giftHxm = [[LWS_GiftHxmIViewController alloc] initWithNibName:NSStringFromClass([LWS_GiftHxmIViewController class]) bundle:nil];
    [self.navigationController pushViewController:giftHxm animated:YES];
    self.segMented.hidden = YES;
    
}
@end
